importClass(android.view.View)
importClass(android.animation.ObjectAnimator)
importClass(android.animation.AnimatorSet)
importClass(android.animation.Animator)
importClass(android.widget.ImageButton)


importClass(android.graphics.Color);
importClass(android.graphics.drawable.GradientDrawable);
importClass(android.text.Spannable);
importClass(android.text.SpannableStringBuilder);
importClass(android.text.style.ForegroundColorSpan);
importClass(android.graphics.LinearGradient);
importClass(android.graphics.Shader);
importClass(android.graphics.Bitmap);
importClass("android.graphics.BitmapFactory");
importClass(android.graphics.BitmapShader);

let ui_config = require("../../ui_config")
let config_templace = require("./config_template")


//设置基础参数
const animationDelay = 250
//屏幕高度
const HEIGHT = device.height
//屏幕宽度
const WIDTH = device.width
//悬浮窗开关状态
let window_status = false
//脚本运行状态
let script_status = false
//日志开关代码
let log_status = false
//脚本线程初始化
let script_thread = threads.start(function(){})
//脚本引擎名称
let script_engine_name = "bh_script"
//要运行的脚本名称
let script_file_name = "script.js"
//全局遮罩层，遮罩状态
let orerlay_window = null, orerlay_status = false;

let open_icon = "robot-3-7.png"
let close_icon = "Robot-1.png"
let run_icon = "bofang.png"
let stop_icon = "zanting.png"
let show_icon = "xianshi.png"
let hide_icon = "yincang.png"
let from_icon = "shezhi.png"
let user_icon = "gerenzhongxin.png"
let quit_icon = "switch.png"
let sound_icon = "sound-filling.png"


//打开遮罩层
function open_orerlay() {
    //打开遮照
    if (orerlay_status) return;
    orerlay_window = floaty.rawWindow(
        <frame bg="#66000000"></frame>
    )
    orerlay_window.setSize(-1, -1)
    orerlay_window.setTouchable(false)
    orerlay_status = !orerlay_status
}

//关闭遮罩层
function close_orerlay() {
    if (!orerlay_status) return;
    orerlay_window.close()
    orerlay_status = !orerlay_status
}

//打开配置项
function open_config() {
    let ui_config_window = floaty.rawWindow(ui_config.ui_xml)
    ui_config.fun.call(ui_config_window)
    
    
}

//关闭配置项

//打开我的

//关闭我的

//封装判断脚本引擎是否存活方法
function isEngineAlive () {
    for (key in engines.all()) {
        if (engines.all()[key].source == script_engine_name+".js") {
            return true
        }
    }
    return false
}

//封装启动脚本方法
function run_script () {
    engines.execScript(script_engine_name, files.read(script_file_name))
}

//封装脚本停止方法
function stop_script() {
    for (key in engines.all()) {
        if (engines.all()[key].source == script_engine_name+".js") {
            engines.all()[key].forceStop()
        }
    }
    return null
}

//定义弹出配置动画
function open_pupwindow(view) {
    animator1 = ObjectAnimator.ofFloat(view, "translationY", HEIGHT, HEIGHT*0.2);
    set = new AnimatorSet();
    set.playSequentially(animator1);
    set.setDuration(animationDelay);
    set.addListener(new Animator.AnimatorListener({
        onAnimationStart: function(animation) {
            view.setVisibility(View.VISIBLE)
        }
    }))
    set.start();
}

//定义打开动画
function open_animator(view) {
    //更加丰富的控制效果
    animator1 = ObjectAnimator.ofFloat(view, "translationX", -1000, 0);
    set = new AnimatorSet();
    set.playSequentially(animator1);
    set.setDuration(animationDelay);
    set.addListener(new Animator.AnimatorListener({
        onAnimationStart: function(animation) {
            view.setVisibility(View.VISIBLE)
        }
    }))
    set.start();
}

//定义点击缩放动画
function click_animator(view) {
    animator1 = ObjectAnimator.ofFloat(view, "scaleX", 1, 2, 1);
    animator2 = ObjectAnimator.ofFloat(view, "scaleY", 1, 2, 1);

    set = new AnimatorSet();
    set.playTogether(animator1, animator2);
    set.setDuration(animationDelay);
    set.addListener(new Animator.AnimatorListener({
        onAnimationStart: function(animation) {
            // view.setVisibility(View.VISIBLE)
        }
    }))
    set.start();
}

//定义关闭动画
function close_animator(view) {
    //更加丰富的控制效果
    animator1 = ObjectAnimator.ofFloat(view, "translationX", 0, -1000);
    set = new AnimatorSet();
    set.playSequentially(animator1);
    set.setDuration(animationDelay);
    set.addListener(new Animator.AnimatorListener({
        onAnimationEnd: function(animation) {
            view.setVisibility(View.GONE)
        }
    }))
    set.start();
}

//定义靠边动画
function abs_animator(view) {
    animator1 = ObjectAnimator.ofFloat(view, "translationX", 0, 80, 0);
    animator2 = ObjectAnimator.ofFloat(view, "translationX", 0, 40, 0);
    animator3 = ObjectAnimator.ofFloat(view, "translationX", 0, 20, 0);
    set = new AnimatorSet();
    set.playSequentially(animator1, animator2, animator3);
    set.setDuration(150);
    set.start();
}

//获取图片base
function get_img_base64(img_path) {
    if (!files.isFile(img_path)) return null;
    let temp_img = images.read(img_path)
    let temp_img_base = "data:image/png;base64,"+images.toBase64(temp_img, "png", 100)
    temp_img.recycle()
    return temp_img_base
}

//获取图标显示状态，默认隐藏
function to_icon_visibility(stat) {
    if (stat == 0) {
        return "gone"
    } else if(stat == 1) {
        return "visible"
    } else {
        return "gone"
    }
}

//设置圆角背景
function setBackgroundRoundRounded(view) {
    gradientDrawable = new GradientDrawable();
    gradientDrawable.setShape(GradientDrawable.RECTANGLE);
    gradientDrawable.setColor(colors.parseColor("#4DA9A9A9"));
    gradientDrawable.setCornerRadius(45);
    gradientDrawable.setSize(50, 50);
    gradientDrawable.setStroke(2, Color.parseColor("#ffffff"))
    view.setBackground(gradientDrawable);
}

//设置pop圆角
function setPopRadio(view) {
    gradientDrawable = new GradientDrawable();
    gradientDrawable.setShape(GradientDrawable.RECTANGLE);
    gradientDrawable.setColor(colors.parseColor("#ffffff"));

    gradientDrawable.setCornerRadii([45, 45, 45, 45, 0,0,0,0,0,0,0,0]);
    gradientDrawable.setSize(50, 50);
    gradientDrawable.setStroke(2, Color.parseColor("#ffffff"))
    view.setBackground(gradientDrawable);
    
}
 
module.exports = function () {
    let close_icon_path = files.join(this.__config__.img_path, close_icon)
    let open_icon_path = files.join(this.__config__.img_path, open_icon)
    
    let close_icon_base = get_img_base64(close_icon_path)
    let open_icon_base = get_img_base64(open_icon_path)

    //获取按钮base
    let run_icon_base = get_img_base64(files.join(this.__config__.img_path, run_icon))
    let stop_icon_base = get_img_base64(files.join(this.__config__.img_path, stop_icon))
    let show_icon_base = get_img_base64(files.join(this.__config__.img_path, show_icon))
    let hide_icon_base = get_img_base64(files.join(this.__config__.img_path, hide_icon))
    let from_icon_base = get_img_base64(files.join(this.__config__.img_path, from_icon))
    let user_icon_base = get_img_base64(files.join(this.__config__.img_path, user_icon))
    let quit_icon_base = get_img_base64(files.join(this.__config__.img_path, quit_icon))

    let sound_icon_base = get_img_base64(files.join(this.__config__.img_path, sound_icon))

    
    
    let window_main_xml = (
        <relative id="main" w="auto" h="auto">

            <horizontal id="box"
                layout_toRightOf="st"
                visibility="gone"
                gravity="center_vertical"
                padding="10dp"

                layout_centerVertical="true"
            >
                {/* 启动暂停 */}
                <vertical marginRight="6dp" id="run_stop">
                    <img w="30dp"
                        h="30dp"
                        scaleType="centerCrop"
                        id="run_stop_icon"
                        src={run_icon_base}
                        circle="true"
                        radius="20"
                        tint="#ffffff"
                        visibility={to_icon_visibility(this.__config__.need_switch.runCheked)}
                    ></img>
                    <text gravity="center" text="启动" textColor="#ffffff" textSize="10sp"></text>
                </vertical>

                {/* 日志 */}
                <vertical marginRight="6dp" id="log">
                    <img w="30dp"
                        h="30dp"
                        scaleType="centerCrop"
                        id="log_icon"
                        src={hide_icon_base}
                        
                        circle="true"
                        radius="20"
                        tint="#ffffff"
                        visibility={to_icon_visibility(this.__config__.need_switch.logChecked)}
                    ></img>
                    <text gravity="center" text="日志" textColor="#ffffff" textSize="10sp"></text>

                </vertical>

                {/* 表单 */}
                <vertical marginRight="6dp" id="from">
                    <img w="30dp"
                        h="30dp"
                        scaleType="centerCrop"
                        id="from_icon"
                        src={from_icon_base}

                        circle="true"
                        radius="20"
                        tint="#ffffff"
                        visibility={to_icon_visibility(this.__config__.need_switch.fromChecked)}
                    ></img>
                    <text gravity="center" text="设置" textColor="#ffffff" textSize="10sp"></text>
                </vertical>


                {/* 我的 */}
                <vertical marginRight="6dp" id="user">
                    <img w="30dp"
                        h="30dp"
                        scaleType="centerCrop"
                        id="user_icon"
                        src={user_icon_base}

                        circle="true"
                        radius="20"
                        tint="#ffffff"
                        visibility={to_icon_visibility(this.__config__.need_switch.userChecked)}
                    ></img>
                    <text gravity="center" text="我的" textColor="#ffffff" textSize="10sp"></text>

                </vertical>


                {/* 退出 */}
                <vertical marginRight="6dp" id="quit">
                    <img w="30dp"
                        h="30dp"
                        scaleType="centerCrop"
                        id="quit_icon"
                        src={quit_icon_base}

                        circle="true"
                        radius="20"
                        tint="#ffffff"
                        visibility={to_icon_visibility(this.__config__.need_switch.quitChecked)}
                    ></img>
                    <text gravity="center" text="退出" textColor="#ffffff" textSize="10sp"></text>

                </vertical>

            </horizontal>

            <img w="40dp" 
                h="40dp" 
                scaleType="centerCrop" 
                id="st" 
                src={close_icon_base}
                layout_centerVertical="true"
                marginRight="20dp"
            ></img>

        </relative>
    )
    let window = floaty.rawWindow(window_main_xml)

    window.setPosition(0, device.height/2)
    setBackgroundRoundRounded(window.box)

    let x = 0, y = 0, windowX, windowY, downTime;

    //滑动监听
    window.box.setOnTouchListener(function(view, event){
        // print("----------------")
        switch (event.getAction()) {
            case event.ACTION_DOWN:
                x = event.getRawX()
                y = event.getRawY()
                windowX = window.getX()
                windowY = window.getY()
                downTime = new Date().getTime()
                return true;
            case event.ACTION_MOVE:
                //移动手指时调整位置
                window.setPosition(windowX + (event.getRawX() - x), windowY + (event.getRawY() - y))

                //如果按下的时间超过1.5秒 判断为长按
                if (new Date().getTime() - downTime > 2000) {
                    // exit();
                }
                return true;
            case event.ACTION_UP:
                //手指弹起的时候如果偏移很小判断为点击
                if (Math.abs(event.getRawY() - y) < 5 && Math.abs(event.getRawX() - x) < 5){
                    //点击
                }
                return true;
        }
        return true
    })
    
    //滑动监听
    window.st.setOnTouchListener(function(view, event){
        // print("----------------")
        switch (event.getAction()) {
            case event.ACTION_DOWN:
                x = event.getRawX()
                y = event.getRawY()
                windowX = window.getX()
                windowY = window.getY()
                downTime = new Date().getTime()
                return true;
            case event.ACTION_MOVE:
                //移动手指时调整位置
                window.setPosition(windowX + (event.getRawX() - x), windowY + (event.getRawY() - y))

                //如果按下的时间超过1.5秒 判断为长按
                if (new Date().getTime() - downTime > 2000) {
                    // exit();
                }
                return true;
            case event.ACTION_UP:
                //手指弹起的时候如果偏移很小判断为点击
                if (Math.abs(event.getRawY() - y) < 5 && Math.abs(event.getRawX() - x) < 5){
                    OnstClick()
                } else {
                    windowX = window.getX()
                    windowY = window.getY()

                    print(windowX)
                    if (windowX != 0) {
                        print("归位")
                        window.setPosition(0, windowY)
                        //播放动画
                        abs_animator(window.st)
                    }
                    
                    //
                }
                return true;
        }
        return true
    })

    //图标主事件
    function OnstClick() {
        if (!window_status) {
            //打开
            open_animator(window.box)
            window.st.setSource(open_icon_base)
        } else {
            //隐藏
            close_animator(window.box)
            window.st.setSource(close_icon_base)
        }
        window_status = !window_status
    }

    //启动和暂停
    window.run_stop.click(() => {
        //播放动画
        click_animator(window.run_stop_icon)
        if (!script_status) {
            //运行
            if (isEngineAlive()) stop_script();
            window.run_stop_icon.setSource(stop_icon_base)
            run_script()
            OnstClick()
        } else {
            //停止
            if (isEngineAlive()) stop_script();
            window.run_stop_icon.setSource(run_icon_base)
        }
        script_status = !script_status
    })

    // 日志
    window.log_icon.click(() => {
        //播放动画
        click_animator(window.log_icon)
        
        if (!log_status) {
            window.log_icon.setSource(show_icon_base)
            console.show()
        } else {
            window.log_icon.setSource(hide_icon_base)
            console.hide()

        }
        log_status = !log_status
    })

    // 设置
    window.from.click(() => {
        //播放动画
        click_animator(window.from_icon)
        threads.start(function(){

        })
        
        // open_config()
        open_orerlay()
        let templace = floaty.rawWindow(config_templace.ui_xml)
        templace.setSize(-1, -1)
        config_templace.fun.call(templace)
        //向上升起
        open_pupwindow(templace.temp_main)
        setPopRadio(templace.temp_main)
        
        templace.temp_body.setVisibility(View.VISIBLE)
        
        
    })

    // 我的
    window.user.click(() => {
        //播放动画
        click_animator(window.user_icon)
        close_orerlay()
    })

    // 退出
    window.quit.click(() => {
        //播放动画
        click_animator(window.quit_icon)
        toastLog("退出")
        engines.stopAll()

        
    })    
    setInterval(() => {}, 1000)
}